package Team.Yaohuo.utils;

import Team.Yaohuo.properties.BaiduProperties;
import Team.Yaohuo.properties.WxProperties;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息推送
 */
@Component
@Slf4j
@Data
public class MessagePushUtil {

    @Autowired
    private WxProperties wxProperties;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private BaiduProperties baiduProperties;

    private static final String MESSAGE_PUSH_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send";

    public void yxMes(String userId, String accsess_token) {

        String date = DateTime.now().toString("yyyy年MM月dd日");
        String ipAddr = httpServletRequest.getRemoteAddr();

        // 调用百度地图获取当前用户ip的地理位置
        String baidu_url = "https://api.map.baidu.com/location/ip?ip=" + ipAddr + "&coor=bd09ll&ak=" + baiduProperties.getAK();
        ResponseEntity<Map> exchange = restTemplate.exchange(baidu_url, HttpMethod.GET, null, Map.class);
        Map content = (Map) exchange.getBody().get("content");
        String address = (String) content.get("address");

        // 1、方案一 文本类型
//        Map<String, Object> meg = new HashMap<>();
//        meg.put("touser", userId);
//        meg.put("msgtype", "textcard");
//        meg.put("agentid", wxProperties.getAgentid());
//        meg.put("textcard", new HashMap<>(){{
//            put("title", "登录通知");
//            put("description", "<div class=\"gray\">"+date+"</div> <div class=\"normal\">当前访问ip地址："+ipAddr+"</div><div class=\"highlight\">"+address+"</div>");
//            put("url", "https://www.jiandaoyun.com");
//            put("btntxt", "详细");
//        }});
//        meg.put("enable_id_trans", 0);
//        meg.put("enable_duplicate_check", 0);
//        meg.put("duplicate_check_interval", 0);
        // 2、方案二 图片文本类型
        Map<String, Object> meg = new HashMap<>();
        List<Object> articlesList = new ArrayList<>();
        Map<String, Object> articlesMap = new HashMap<>();
        articlesMap.put("title", "登录通知");
        // todo 先写死
        articlesMap.put("thumb_media_id", "3Dm9NlWEouSSmzXNiuDbl5dmW1AAJyL1B4n_RfDdYvHnjsfz31s_DuJdayI4AQc5CxK4yrDoFFjUqGAYMbvJ7wA");
        articlesMap.put("author", "liuxintong");
        articlesMap.put("content_source_url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww9cbdb9ca4b0d4236&redirect_uri=http%3A%2F%2Fwww.yaohuo.team%2FgetWxAuto&state=yaohuokeji&response_type=code&scope=snsapi_base&agentid=1000014#wechat_redirect");
        articlesMap.put("content", "22222");
        articlesMap.put("digest", "点击查看登录详情");
        articlesList.add(articlesMap);
        meg.put("touser", userId);
        meg.put("msgtype", "mpnews");
        meg.put("agentid", wxProperties.getAgentid());
        meg.put("mpnews", new HashMap<>() {{
            put("articles", articlesList);
        }});
        meg.put("enable_id_trans", 0);
        meg.put("enable_duplicate_check", 0);
        meg.put("duplicate_check_interval", 0);


        HttpEntity<Map<String, Object>> mapHttpEntity = new HttpEntity<>(meg);
        log.info("封装的请求体为:{}", mapHttpEntity);
        ResponseEntity<Map> responseEntity = restTemplate.exchange(MESSAGE_PUSH_URL + "?access_token=" + accsess_token, HttpMethod.POST, mapHttpEntity, Map.class);
        log.info("请求发送完毕，当前响应的信息为:{}", responseEntity);
        if (responseEntity.getBody() != null) {
            Integer errcode = (Integer) responseEntity.getBody().get("errcode");
            String msgid = (String) responseEntity.getBody().get("msgid");
            if (errcode == 0) {
                log.info("消息推送成功，当前messageId为:{}", msgid);
            } else {
                log.error("消息推送失败，返回错误码为:{}, 请前往https://developer.work.weixin.qq.com/document/path/96213进行查看", errcode);
            }
        }

    }
}
